
package me.zhengjie.service.impl;

import me.zhengjie.domain.AppDakaConfig;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.system.service.RoleService;
import me.zhengjie.modules.system.service.UserService;
import me.zhengjie.modules.system.service.dto.RoleSmallDto;
import me.zhengjie.modules.system.service.dto.UserDto;
import me.zhengjie.utils.*;
import lombok.RequiredArgsConstructor;
import me.zhengjie.repository.AppDakaConfigRepository;
import me.zhengjie.service.AppDakaConfigService;
import me.zhengjie.service.dto.AppDakaConfigDto;
import me.zhengjie.service.dto.AppDakaConfigQueryCriteria;
import me.zhengjie.service.mapstruct.AppDakaConfigMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.util.*;
import java.io.IOException;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author IQW
* @date 2022-07-18
**/
@Service
@RequiredArgsConstructor
public class AppDakaConfigServiceImpl implements AppDakaConfigService {

    private final AppDakaConfigRepository appDakaConfigRepository;
    private final AppDakaConfigMapper appDakaConfigMapper;
    private final UserService userService;
    private final RoleService roleService;


    @Override
    public Map<String,Object> queryAll(AppDakaConfigQueryCriteria criteria, Pageable pageable){

        //获取最小权限
        Integer currentLevel =  Collections.min(roleService.findByUsersId(SecurityUtils.getCurrentUserId()).stream().map(RoleSmallDto::getLevel).collect(Collectors.toList()));
        System.out.println("min level:"+currentLevel);
        if(currentLevel<=2){
            //管理员查看所有
        }else{
            //查看当前责任区
            Long userId = SecurityUtils.getCurrentUserId();
            UserDto user = userService.findById(userId);
            criteria.setAreaId(user.getAreaId());
        }
        Page<AppDakaConfig> page = appDakaConfigRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(appDakaConfigMapper::toDto));
    }

    @Override
    public List<AppDakaConfigDto> queryAll(AppDakaConfigQueryCriteria criteria){
        return appDakaConfigMapper.toDto(appDakaConfigRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public AppDakaConfigDto findById(Integer id) {
        AppDakaConfig appDakaConfig = appDakaConfigRepository.findById(id).orElseGet(AppDakaConfig::new);
        ValidationUtil.isNull(appDakaConfig.getId(),"AppDakaConfig","id",id);
        return appDakaConfigMapper.toDto(appDakaConfig);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AppDakaConfigDto create(AppDakaConfig resources) {

        //查询责任区
        Long userId = SecurityUtils.getCurrentUserId();
        UserDto user = userService.findById(userId);

        if(null == user.getAreaId()){
            throw new BadRequestException("抱歉，当前登录用户责任区未设置");
        }
        if(null == resources.getAreaId()){
            throw new BadRequestException("请选择责任区");
        }

        if(!user.getAreaId().equals(resources.getAreaId())){
            throw new BadRequestException("抱歉，只能配置自己所属责任区");
        }
//        resources.setAreaId(user.getAreaId());

        if((null == resources.getLat() || StringUtils.isEmpty(resources.getLat()))
                && (null == resources.getLon() || StringUtils.isEmpty(resources.getLon()))
                && (null == resources.getWifi() || StringUtils.isEmpty(resources.getWifi())) ){
            throw new BadRequestException("抱歉，经纬度与WIFI设置不能同时为空");
        }

        //检测1个区域，只能1条规则
        if(null != appDakaConfigRepository.findByAreaId(resources.getAreaId())){
            throw new BadRequestException("抱歉，该责任区已存在考勤规则");
        }

        if((null == resources.getLat() || StringUtils.isEmpty(resources.getLat()))
                || (null == resources.getLon() || StringUtils.isEmpty(resources.getLon()))  ){
            //强制设为空
            resources.setLat(null);
            resources.setLon(null);
            resources.setAddress("");
        }
        return appDakaConfigMapper.toDto(appDakaConfigRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(AppDakaConfig resources) {
        AppDakaConfig appDakaConfig = appDakaConfigRepository.findById(resources.getId()).orElseGet(AppDakaConfig::new);
        ValidationUtil.isNull( appDakaConfig.getId(),"AppDakaConfig","id",resources.getId());
        appDakaConfig.copy(resources);

        Long userId = SecurityUtils.getCurrentUserId();
        UserDto user = userService.findById(userId);
        if(null == user.getAreaId()){
            throw new BadRequestException("抱歉，当前登录用户责任区未设置");
        }
        if(null == resources.getAreaId()){
            throw new BadRequestException("请选择责任区");
        }

        if(!user.getAreaId().equals(resources.getAreaId())){
            throw new BadRequestException("抱歉，只能配置自己所属责任区");
        }

        if(!resources.getAreaId().equals(appDakaConfig.getAreaId())){
            if(null != appDakaConfigRepository.findByAreaId(resources.getAreaId())){
                throw new BadRequestException("抱歉，该责任区已存在考勤规则");
            }
        }
        if((null == resources.getLat() || StringUtils.isEmpty(resources.getLat()))
                && (null == resources.getLon() || StringUtils.isEmpty(resources.getLon()))
                && (null == resources.getWifi() || StringUtils.isEmpty(resources.getWifi())) ){
            throw new BadRequestException("抱歉，经纬度与WIFI设置不能同时为空");
        }

        if((null == resources.getLat() || StringUtils.isEmpty(resources.getLat()))
                || (null == resources.getLon() || StringUtils.isEmpty(resources.getLon()))  ){
            //强制设为空
            appDakaConfig.setLat(null);
            appDakaConfig.setLon(null);
            appDakaConfig.setAddress("");
        }
        appDakaConfigRepository.save(appDakaConfig);
    }

    @Override
    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {
            appDakaConfigRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<AppDakaConfigDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (AppDakaConfigDto appDakaConfig : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("责任区ID", appDakaConfig.getAreaId());
            map.put("2或4时间点", appDakaConfig.getNum());
            map.put("地址", appDakaConfig.getAddress());
            map.put("经度", appDakaConfig.getLon());
            map.put("纬度", appDakaConfig.getLat());
            map.put(" time1",  appDakaConfig.getTime1());
            map.put(" time2",  appDakaConfig.getTime2());
            map.put(" time3",  appDakaConfig.getTime3());
            map.put(" time4",  appDakaConfig.getTime4());
            map.put("允许WIFI名称", appDakaConfig.getWifi());
            map.put("范围多少米", appDakaConfig.getFanwei());
            map.put("状态  0缺卡，1正常，2早退，3迟到", appDakaConfig.getStatus());
            map.put(" createTime",  appDakaConfig.getCreateTime());
            map.put(" updateTime",  appDakaConfig.getUpdateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}